package com.sq.partner.manager.controller;

import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.HaidaInfo;
import com.sq.partner.manager.service.HaidaService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author lxy
 * 2022/3/31 17:08
 */
@Controller
@RequestMapping("/haida")
public class HaidaReconciliationController {
	
	private final Logger logger = LogUtil.getLog(HaidaReconciliationController.class);
	
	@Resource
	private HaidaService haidaService;
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {
		return "haida/policyReconciliation";
	}
	
	@RequestMapping(value = "/queryReconciliationInfo", method = RequestMethod.POST)
	@ResponseBody
	public Page queryReconciliationInfo(@RequestBody Map<String, Object> haidaInfo) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		String haidaJsonStr = mapper.writeValueAsString(haidaInfo);
		HashMap haidaMap = mapper.readValue(haidaJsonStr, HashMap.class);
		haidaMap.remove("pageIndex");
		Page page = haidaService.queryHaidaInfoPage(haidaInfo);
		page.setMap(haidaMap);
		return page;
	}
	
	@RequestMapping(value = "/terminationOfInsurance")
	@ResponseBody
	public Result terminationOfInsurance(String serialNumber, String orderNo, String polNo) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("serialNumber", serialNumber);
		map.put("orderNo", orderNo);
		map.put("polNo", polNo);
		long count = haidaService.queryHaidaReconciliationCount(map);
		if (count != 1) {
			return Result.error("系统错误，请联系管理员处理");
		}
		Map<String, String> result = haidaService.terminationOfThePolicy(map);
		if ("0000".equals(result.get("resultCode"))) {
			return Result.success(result.get("resultInfo"));
		} else {
			return Result.error(result.get("resultInfo"));
		}
	}
	
	@RequestMapping(value = "/exportExcel")
	@ResponseBody
	public void exportExcel(HttpServletResponse response, HttpServletRequest request, String serialNumber,
	                        String orderNo, String polNo, String bbrName, String startTransDate, String endTransDate,
	                        String effDate, String termDate, String accountFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("serialNumber", serialNumber);
		map.put("orderNo", orderNo);
		map.put("polNo", polNo);
		map.put("bbrName", bbrName);
		map.put("startTransDate", startTransDate);
		map.put("endTransDate", endTransDate);
		map.put("effDate", effDate);
		map.put("termDate", termDate);
		map.put("accountFlag", accountFlag);
		if (map.containsKey("startTransDate") && map.containsKey("endTransDate")) {
			String start = (String) map.get("startTransDate");
			String end = (String) map.get("endTransDate");
			if (start != null && !start.equals("")) {
				map.put("startTransDate", start + " 00:00:00");
			}
			if (end != null && !end.equals("")) {
				map.put("endTransDate", end + " 23:59:59");
			}
		}
		List<HaidaInfo> haidaInfoList = haidaService.queryHaidaInfoList(map);
		String fileName = "海达对账信息表";
		String sheetName = "海达对账信息";
		// 列数
		int columnNumber = 11;
		// 列宽
		int[] columnWidth = {5, 15, 15, 25, 10, 10, 20, 20, 20, 10, 10};
		// 列名
		String[] columnName = {"序号", "交易流水号", "订单号", "保单号", "保费", "保额", "交易日期", "保险起期", "保险止期",
				"被保险人", "对账标识"};
		// 序号
		int count = 1;
		List<String[]> tempList = new ArrayList<String[]>();
		for (HaidaInfo h : haidaInfoList) {
			tempList.add(new String[]{String.valueOf(count++), h.getSerialNumber(), h.getOrderNo(), h.getPolNo(),
					h.getPrem(), h.getAmt(), h.getTransDate(), h.getEffDate(), h.getTermDate(), h.getBbrName(), h.getAccountFlag()});
		}
		// 海达信息的二维数组【列】【行】
		String[][] haidaInfos = tempList.toArray(new String[][]{});
		HSSFWorkbook wb = haidaService.generateHssWorkBook(sheetName, columnNumber, columnWidth, columnName, haidaInfos);
		response.setContentType("application/ms-excel;charset=utf-8");
		String userAgent = request.getHeader("user-agent").toLowerCase();
		if (userAgent.contains("msie") || userAgent.contains("trident") || userAgent.contains("edge")) {
			// IE浏览器
			fileName = URLEncoder.encode(fileName, "UTF-8");
		} else {
			// 非IE浏览器
			fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
		}
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
		OutputStream os = response.getOutputStream();
		try {
			wb.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			os.close();
		}
	}
}
